package io.gitee.zhangbinhub.acp.core.file.pdf.fonts

import com.itextpdf.kernel.font.PdfFontFactory
import com.itextpdf.layout.font.FontProvider
import com.itextpdf.text.pdf.BaseFont
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.acp.core.common.CommonTools.getFontFold
import io.gitee.zhangbinhub.acp.core.common.log.LogFactory.Companion.getInstance
import java.io.File

object FontLoader {
    private val log = getInstance(FontLoader::class.java)

    private val fontFold: String
        get() {
            val fold = File(getFontFold())
            if (!fold.exists()) {
                if (!fold.mkdirs()) {
                    log.error("mkdirs failed : ${fold.canonicalPath}")
                }
            }
            return fold.canonicalPath
        }

    @JvmStatic
    @JvmOverloads
    fun getFontProvider(ttcPath: String?, ttcIndex: Int = 0): FontProvider? = try {
        FontProvider().apply {
            val font = if (CommonTools.isNullStr(ttcPath)) {
                File(fontFold + File.separator + "SIMSUN.TTC")
            } else {
                File(ttcPath!!)
            }
            //设置字体
            val pdfFont = PdfFontFactory.createTtcFont(
                font.getCanonicalPath(), ttcIndex,
                BaseFont.IDENTITY_H,
                PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED,
                false
            )
            this.addFont(pdfFont.fontProgram, BaseFont.IDENTITY_H)
        }
    } catch (e: Exception) {
        log.error(e.message, e)
        null
    }

    @JvmStatic
    @JvmOverloads
    fun getBaseFont(ttcPath: String?, ttcIndex: Int = 0): BaseFont? = try {
        val font = if (CommonTools.isNullStr(ttcPath)) {
            File(fontFold + File.separator + "SIMSUN.TTC")
        } else {
            File(ttcPath!!)
        }
        BaseFont.createFont(font.getCanonicalPath() + ",$ttcIndex", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED)
    } catch (e: Exception) {
        log.error(e.message, e)
        null
    }
}
